<?php
/**
 * 缓存清理命令：替代各种 cache:clear 命令
 */

namespace Jammiest\SwigeCore\Console\Commands\Cache;

use Jammiest\SwigeCore\Console\Commands\Command;
use Jammiest\SwigeCore\Tools\Path;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;

#[AsCommand(name: 'cache:clear')]
class ClearCommand extends Command
{

    protected function configure()
    {
        $this->setDescription('清除应用缓存');
    }

    protected function execute(InputInterface $input, OutputInterface $output):int
    {
        $io = new SymfonyStyle($input, $output);
        $io->title('清除应用缓存');
        
        try {
            $cacheDir = Path::getBasePath('storage/framework/cache');
            // $cacheDir = storage_path('framework/cache');
            
            if (is_dir($cacheDir)) {
                $this->clearDirectory($cacheDir);
                $io->writeln('✅ 配置缓存已清除');
            }
            
            $viewCacheDir = Path::getBasePath('storage/framework/views');
            // $viewCacheDir = storage_path('framework/views');
            if (is_dir($viewCacheDir)) {
                $this->clearDirectory($viewCacheDir);
                $io->writeln('✅ 视图缓存已清除');
            }
            
            $io->success('所有缓存已清除完毕');
            return Command::SUCCESS;
            
        } catch (\Exception $e) {
            $io->error('缓存清除失败: ' . $e->getMessage());
            return Command::FAILURE;
        }
    }

    private function clearDirectory($dir)
    {
        $files = glob($dir . '/*');
        foreach ($files as $file) {
            if (is_file($file)) {
                unlink($file);
            }
        }
    }
}